package auth

import (
	"fmt"
	"goProject/cfg"
	"goProject/db"
	"goProject/table"
	"strconv"
	"time"

	"github.com/redis/go-redis/v9"

	"gitee.com/ruige_fun/util/rlog"

	"github.com/kataras/iris/v12/middleware/jwt"
)

func init() {
	_, err := db.RunConfig.Get("登录Token有效时间（秒）：")
	if err == redis.Nil {
		_ = db.RunConfig.Set("登录Token有效时间（秒）：", "3600")
	}
}

// NewToken 生成token
func NewToken(user table.User, ip string) string {
	content, _ := db.RunConfig.Get("登录Token有效时间（秒）：")
	second, _ := strconv.Atoi(content)
	if second <= 180 {
		second = 180
	}
	signer := jwt.NewSigner(jwt.HS256, []byte(cfg.Password.JwtSecretKey), time.Second*time.Duration(second))
	sign, err := signer.Sign(&jwt.Claims{
		ID:     fmt.Sprint(user.ID),
		Issuer: ip,
	})
	if err != nil {
		rlog.Error("生成JWT签名失败：", err)
		return ""
	}
	return string(sign)
}

// ParseToken 解析token
func ParseToken(token string, ip string) (jwt.Claims, error) {
	verify, err := jwt.Verify(jwt.HS256, []byte(cfg.Password.JwtSecretKey), []byte(token))
	if err != nil {
		return jwt.Claims{}, fmt.Errorf("token验证失败1")
	}
	var it jwt.Claims
	err = verify.Claims(&it)
	if err != nil {
		return jwt.Claims{}, fmt.Errorf("token验证失败2")
	}
	if it.Issuer != ip {
		return jwt.Claims{}, fmt.Errorf("token验证失败1")
	}
	return it, nil
}
